package help

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"math"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

// OpenBrowsers 打开浏览器
func OpenBrowsers(uri string) error {
	// 不同平台启动指令不同
	var commands = map[string]string{
		"windows": "explorer",
		"darwin":  "open",
		"linux":   "xdg-open",
	}

	run, ok := commands[runtime.GOOS]
	if !ok {
		return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS)
	}

	cmd := exec.Command(run, uri)
	return cmd.Run()
}

// Split 分割路径
func Split(fullPath string) (dir, file, ext string) {
	var tmpFile string

	dir, tmpFile = filepath.Split(fullPath)
	ext = filepath.Ext(tmpFile)

	index := strings.LastIndex(tmpFile, ext)
	if index >= 0 {
		file = tmpFile[:index]
	} else {
		file = tmpFile
	}

	return
}

// GetDurationString 00:02:45
func GetDurationString(duration time.Duration) string {
	hour := int(math.Floor(duration.Hours()))
	duration = duration - time.Duration(hour)*time.Hour

	minute := int(math.Floor(duration.Minutes()))
	duration = duration - time.Duration(minute)*time.Minute

	second := int(duration.Seconds())

	return fmt.Sprintf("%02d:%02d:%02d", hour, minute, second)
}

const rawEncode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ac"

var rawEncoding = base64.NewEncoding(rawEncode).WithPadding(base64.NoPadding)

func GetUID(size ...uint) string {
	buffSize := uint(16)
	if len(size) > 0 {
		buffSize = size[0]
	}
	if buffSize == 0 {
		return ""
	}

	buffer := make([]byte, buffSize)
	_, _ = rand.Read(buffer)

	data := rawEncoding.EncodeToString(buffer)
	return data[:buffSize]
}
